package config

import (
	"strings"
)

// Section 配置文件的section，包含名字和多个配置选项键值对
type Section struct {
	name    string
	kvNodes []*KvNode
}

// Name 返回Section的名字
func (sec *Section) Name() string {
	return sec.name
}

// SetName 设置section的name
func (sec *Section) SetName(name string) error {
	if strings.Trim(name, " ") == "" {
		return ErrorFooEmptyString
	}
	sec.name = name
	return nil
}

// GetKvNode 根据key返回对应的键值对
// 错误：没有相应key的配置键值对
func (sec *Section) GetKvNode(key string) (*KvNode, error) {
	if strings.Trim(key, " ") == "" {
		return nil, ErrorFooEmptyString
	}
	for _, kvNode := range sec.kvNodes {
		if kvNode.Key() == key {
			return kvNode, nil
		}
	}
	// Error: dont have coresponding kvpair
	return nil, ErrorFooNoItem
}

// SetKvNode 根据key找到相应键值对选项，并赋予新值
func (sec *Section) SetKvNode(key string, newVal string) error {
	if strings.Trim(key, " ") == "" || strings.Trim(newVal, " ") == "" {
		return ErrorFooEmptyString
	}
	kvNode, err := sec.GetKvNode(key)
	if err != nil {
		return ErrorFooNoItem
	}
	kvNode.SetVal(newVal)
	return nil
}

// AddKvNode 为section增加一个新的键值对配置项
// kvstr 应该满足 " = "
func (sec *Section) AddKvNode(kvstr string) error {
	if strings.Trim(kvstr, " ") == "" {
		return ErrorFooEmptyString
	}
	kvNode, err := NewKvNode(kvstr)
	if err != nil {
		return err
	}
	sec.kvNodes = append(sec.kvNodes, kvNode)
	return nil
}

// KvNodes 返回section的所有键值对
func (sec *Section) KvNodes() []*KvNode {
	return sec.kvNodes
}

// NewSection 创建一个名为name的section
// kvstrs包含许多的kvsrt，具有形式 " = "，从而创建相应键值对
func NewSection(name string, kvstrs []string) (*Section, error) {
	if strings.Trim(name, " ") == "" || len(kvstrs) == 0 {
		return nil, ErrorFooEmptyString
	}
	section := new(Section)
	section.SetName(name)
	for _, kvstr := range kvstrs {
		err := section.AddKvNode(kvstr)
		if err != nil {
			return nil, err
		}
	}
	return section, nil
}
